package com.zhuyuan.core.handler;

import com.zhuyuan.core.enums.ResultCodeEnum;
import com.zhuyuan.core.exception.TokenException;
import com.zhuyuan.core.util.Result;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 张琳凯
 * @Description: TODO
 * @DateTime: 2025/2/24 16:42
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常处理
     *
     * @param e the e
     */
    @ExceptionHandler(Exception.class)
    public Result handleGlobalException(Exception e) throws Exception {

        log.error("=====全局异常信息: {}", e.getMessage(), e);
        return Result.fail(ResultCodeEnum.FAILED.code, e.getLocalizedMessage());
    }
    /**
     * 处理 IllegalArgumentException 异常
     *
     * @param e the e
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("=====ResponseStatusException 异常信息: {}", e.getMessage(), e);
        return Result.fail(e.getMessage());
    }
    /**
     * 处理 ResponseStatusException 异常
     *
     * @param e the e
     */
    @ExceptionHandler(ResponseStatusException.class)
    public Result handleResponseStatusException(ResponseStatusException e) {
        log.error("=====ResponseStatusException 异常信息: {}", e.getMessage(), e);
        return Result.fail(e.getStatus().value(), e.getReason());
    }

    @ExceptionHandler(TokenException.class)
    public Result<?> handleTokenException(HttpServletRequest request, TokenException e) {

        log.error("授权相关异常==>errorCode:{}, exception:{}", HttpStatus.UNAUTHORIZED.value(), e.getMessage());
        return Result.fail(ResultCodeEnum.FAILED.getCode(), e.getMessage());
    }
}
